/*--------------------------------------------------------------------------------*/
#ifndef __GRAPHIC_TEXTURE__
#define __GRAPHIC_TEXTURE__
/*--------------------------------------------------------------------------------*/
#include "primitives.h"
#include "object.h"
#include "ref_to_.h"
#include "util.h"
#include "graphic_image_loader_tga.h"
#include <GL/gl.h>
/*--------------------------------------------------------------------------------*/
class GRAPHIC_TEXTURE : public OBJECT
{

	// -- PUBLIC

public:

    DECLARE_REF( GRAPHIC_TEXTURE );

    // .. CONSTRUCTORS

    GRAPHIC_TEXTURE() : OBJECT(), Id( 0 )
    {
    }

    virtual ~GRAPHIC_TEXTURE()
    {
    	if( Id )
    	{
    		glDeleteTextures( 1, &Id );
    	}
    }

    // .. METHODS

    VOID SetId( UINT32 id )
    {
    	Id = id;
    }

    UINT32 GetId()
    {
		return Id;
    }

    VOID BindTexture() const
    {
    	glEnable( GL_TEXTURE_2D );
    	glBindTexture( GL_TEXTURE_2D, Id );
    	DEBUG_CheckOpenGL();
    }

    VOID LoadTextureFromFile( const TEXT & file_name )
    {
		GRAPHIC_IMAGE::REF
			image;

    	image = GRAPHIC_IMAGE_LOADER_TGA::LoadFromFile( file_name );

		if( !image.IsNull() )
		{
			glEnable( GL_TEXTURE_2D );
			glGenTextures( 1, &Id );
			glBindTexture( GL_TEXTURE_2D, Id );

			glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
			glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );

			glTexImage2D(
				GL_TEXTURE_2D,
				0,
				GL_RGBA8,
				image->GetWidth(),
				image->GetHeight(),
				0,
				image->GetFormat(),
				GL_UNSIGNED_BYTE,
				image->GetArray()
				);

			DEBUG_CheckOpenGL();

			glDisable( GL_TEXTURE_2D );
		}
		else
		{
			DEBUG_Log( "Warning : Texture not loaded : " + file_name );
		}
    }

    // .. FUNCTIONS

    static GRAPHIC_TEXTURE::REF CreateTextureFromFile( const TEXT & file_name )
    {
		GRAPHIC_TEXTURE::REF
			result;

		result.New();
		result->LoadTextureFromFile( file_name );

		return result;
    }

private:

    // .. ATTRIBUTES

    UINT32
		Id;


};
/*--------------------------------------------------------------------------------*/
#endif
